/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function (root) {
  let res = []
  function postOrder (root) {
    if (root === null) {
      res.push('#')
      return
    }
    postOrder(root.left)
    postOrder(root.right)
    res.push(root.val)
  }
  postOrder(root)
  return res.join(',')
};

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
var deserialize = function (data) {
  let nodes = data.split(',') // 先分成数组
  function myDeserialize (nodes) {
    if (nodes.length === 0) {
      return null
    }
    let rootVal = nodes.pop() // 弹出头结点
    if (rootVal === '#') return null
    // 先遍历右子树 这个是后续遍历的特点决定的
    let root = new TreeNode(rootVal)
    root.right = myDeserialize(nodes)
    root.left = myDeserialize(nodes)
    return root
  }
  return myDeserialize(nodes)
};

/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */